<?php
namespace app\admin\controller;
use think\Db;


class Statistics extends Base
{
    public function __construct(){
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '数据统计';

        $this->assign([
            'page_info'=>$page_info
        ]);
    }

    public function indexForAjax(){
        header('Content-Type: application/json');
        $map_params = [
            ['key'=>'sale_id','type'=>'='],
            ['key'=>'team_id','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        if (isSearchParam('start_time')) {
            $map[] = ['ctime','>=',input('start_time')];
        }
        if (isSearchParam('end_time')) {
            $map[] = ['ctime','<=',input('end_time')];
        }

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('limit',20)
        ];
        $sort = [
            input('sort','id'),
            input('sortOrder','desc')
        ];

        $list = Db::name('statistics')->where($map)->order($sort[0],$sort[1])->paginate($page_param);
        $list = $list->toarray();

        $data = ['rows'=>[],'total'=>$list['total']];

        $list = $list['data'];
        foreach ($list as $k => $vo) {
            $list[$k]['sale_name'] = Db::name('sale')->where('id',$vo['sale_id'])->value('truename');
            $list[$k]['team_name'] = Db::name('team')->where('id',$vo['team_id'])->value('name');
            $list[$k]['hjzx_ratio'] = empty($vo['hjzx_num']) ? 0 : round($vo['hjzx_success'] / $vo['hjzx_num'] * 100,2);
        }

        $data['rows'] = $list;


        $response = input('callback') . '(' . json_encode($data) . ')';
        echo $response;
    }

    public function index(){
        $sales = Db::name('sale')->select();
        $sales = arrayParamExtract($sales,'id','truename');

        $teams = Db::name('team')->select();
        $teams = arrayParamExtract($teams,'id','name');

        $search_params = [
            [
                ['key'=>'sale_id','name'=>'销售','type'=>'select1_1','params'=>$sales],
                ['key'=>'team_id','name'=>'团队','type'=>'select1_1','params'=>$teams],
                ['key'=>'start_time','name'=>'开始时间','type'=>'date'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'date'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params,
            'sales'=>$sales
        ]);

        return view('index', [
           'data_url'=>url('indexForAjax',request()->param())
        ]);
    }



    public function customerData(){
        $map_params = [
            // ['key'=>'team_id','type'=>'=']
            ['key'=>'is_valid','type'=>'=']
        ];
        $map = getSearchParam($map_params);
        if (isSearchParam('team_id')) {
            $sale_ids = Db::name('sale')->where('team_id',input('team_id'))->column('id');
            $map[] = ['sale_id','in',$sale_ids];
            $sale_map = [
                ['team_id','=',input('team_id')]
            ];
        }
        // $sale_map = $map;
        switch (input('date_type')) {
            case '1':
                $date = date('Y-m-d',strtotime('-1 days'));
                $map[] = ['ctime','between',[strtotime($date.' 00:00:00'),strtotime($date.' 23:59:59')]];
                break;
            case '2':
                $week_start = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
                // $map[] = ['ctime','>',date('Y-m-d 00:00:00',$week_start)];
                $map[] = ['ctime','>',$week_start];
                break;
            case '10':
                if (!empty(input('start_time'))) {
                    $map[] = ['ctime','>=',strtotime(input('start_time'))];
                }
                if (!empty(input('end_time'))) {
                    $map[] = ['ctime','<=',strtotime(input('end_time'))];
                }
                break;
            default:
                $map[] = ['ctime','>',strtotime(date('Y-m-d 00:00:00'))];
                break;
        }

        $map[] = ['is_gh','=',0];
        $list = Db::name('customer')->field('sale_id,count(*) as num')->where($map)->group('sale_id')->select();
        $customers = [];
        foreach ($list as $k => $vo) {
            $customers[$vo['sale_id']] = $vo['num'];
        }
        $list = Db::name('sale')->where($sale_map)->select();
        foreach ($list as $k => $vo) {
            $list[$k]['num'] = empty($customers[$vo['id']])?0:$customers[$vo['id']];
            $list[$k]['team_name'] = Db::name('team')->where('id',$vo['team_id'])->value('name');
        }

        $teams = Db::name('team')->select();
        $teams = arrayParamExtract($teams,'id','name');
        $search_params = [
            'teams'=>$teams,
            'date_type'=>['今日','昨日','本周',10=>'自定义']
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);

        if (input('is_group') == 1) {
            $new_list = [];
            foreach ($list as $k => $vo) {
                if (empty($new_list[$vo['team_id']])) {
                    $new_list[$vo['team_id']] = [
                        'team_name'=>Db::name('team')->where('id',$vo['team_id'])->value('name'),
                        'data'=>[]
                    ];
                }
                $new_list[$vo['team_id']]['data'][] = $vo;
            }
            $list = array_values($new_list);
        }else{
            $list = [['data'=>$list]];
        }

        return $list;
    }

    public function customer(){
        $list = $this->customerData();

        return view('customer', [
            'list'=>$list,
        ]);
    }

    // public function customer(){
    //     if (!isSearchParam('start_time')) {
    //         $this->request->start_time = date('Y-m-01');
    //     }

    //     $search_params = [
    //         [
    //             ['key'=>'start_time','name'=>'开始时间','type'=>'date'],
    //             ['key'=>'end_time','name'=>'结束时间','type'=>'date'],
    //         ]
    //     ];
    //     $this->assign([
    //         'search_params'=>$search_params
    //     ]);


    //     $list = $this->getData();

    //     $fields = ['cpsl','bgsl','xmpf','pg_charge','cspf','total'];
    //     $total = [
    //         'name'=>'统计',
    //     ];
    //     foreach ($fields as $field) {
    //         $total[$field] = array_sum(array_column($list,$field));
    //     }
        
    //     $params = input('get.');
    //     return view('index', [

    //     ]);
    // }

    public function export(){
        set_time_limit ( 0 );
        ini_set('memory_limit','40960M');

        $list = $this->customerData();
        
        $data = [];
        $title = ['团队','姓名','客户数'];
        foreach ($list as $k => $team) {
            foreach ($team['data'] as $vo) {
                $tmp = [
                    $vo['team_name'],
                    $vo['truename'],$vo['num']
                ];
                $data[] = $tmp;
            }
        }
        exportCsv(date('YmdHis'),$title,$data);
    }


    public function proposal(){
        $map_params = [];
        $map = getSearchParam($map_params);
        switch (input('date_type')) {
            case '1':
                $date = date('Y-m-d',strtotime('-1 days'));
                $map[] = ['ctime','between',[$date.' 00:00:00',$date.' 23:59:59']];
                break;
            case '2':
                $week_start = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
                $map[] = ['ctime','>',date('Y-m-d 00:00:00',$week_start)];
                break;
            case '10':
                if (!empty(input('start_time'))) {
                    $map[] = ['ctime','>=',input('start_time')];
                }
                if (!empty(input('end_time'))) {
                    $map[] = ['ctime','<=',input('end_time')];
                }
                break;
            default:
                $map[] = ['ctime','>',date('Y-m-d 00:00:00')];
                break;
        }

        $sale_ids = Db::name('team')->where('sale_id','>',0)->column('sale_id');
        $list = Db::name('sale')->where('id','in',$sale_ids)->select();
        
        foreach ($list as $k => $vo) {
            $search_map = $map;
            $search_map[] = ['team_sid','=',$vo['id']];
            $list[$k]['num'] = Db::name('customer_proposal')->where($search_map)->count();
        }

        $search_params = [
            // 'teams'=>Db::name('team')->select(),
            'date_type'=>['今日','昨日','本周',10=>'自定义']
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
        
        $page_info = $this->page_info;
        $page_info['title'] = '建议统计';
        return view('proposal', [
            'list'=>$list,
            'page_info'=>$page_info
        ]);
    }

    public function hjzx(){
        $map = [];
        if (isSearchParam('sale_id')) {
            $map[] = ['id','=',input('sale_id')];
        }
        if (isSearchParam('team_id')) {
            $map[] = ['team_id','=',input('team_id')];
        }
        $sales = Db::name('sale')->where($map)->select();
        foreach ($sales as $k => $vo) {
            $sales[$k]['team_name'] = Db::name('team')->where('id',$vo['team_id'])->value('name');
        }
        $start_time = input('?start_time') ? strtotime(input('start_time')) : strtotime(date('Y-m-d'));
        $end_time = input('?end_time') ? strtotime(input('end_time').' 23:59:59') : strtotime(date('Y-m-d 23:59:59'));

        $list = [];
        if (input('time_particle',10) == 10) {
            foreach ($sales as $k => $vo) {
                $map = [
                    ['ctime','between',[$start_time,$end_time]],
                    ['sale_id','=',$vo['id']]
                ];
                $tmp = [
                    'time_name'=>timeDef($start_time,'','Y-m-d').'~'.timeDef($end_time,'','Y-m-d'),
                    'team_name'=>$vo['team_name'],
                    'sale_name'=>$vo['truename']
                ];        
                $tmp['contact_num'] = Db::name('contact')->where($map)->count();
                $tmp['hjzx_num'] = Db::name('hjzx_record')->where($map)->count();
                if ($tmp['hjzx_num'] == 0) {
                    continue;
                }
                $map[] = ['bill','>',0];
                $tmp['bill_num'] = Db::name('hjzx_record')->where($map)->count();
                $tmp['bill_total'] = Db::name('hjzx_record')->where($map)->sum('bill');
                $tmp['bill_ratio'] = $tmp['hjzx_num']?round($tmp['bill_num']/$tmp['hjzx_num']*100,2):0;

                $list[] = $tmp;
            }
        }else{
            switch (input('time_particle',1)) {
                case '0': $time_particle = '+1 hours'; break;
                case '2': $time_particle = '+1 month'; break;
                default: $time_particle = '+1 days'; break;
            }
            while ($start_time <= $end_time) {
                $next_time = strtotime($time_particle,$start_time);
                foreach ($sales as $k => $vo) {
                    $map = [
                        ['ctime','between',[$start_time,$next_time]],
                        ['sale_id','=',$vo['id']]
                    ];
                    $tmp = [
                        'time_name'=>timeDef($start_time),
                        'team_name'=>$vo['team_name'],
                        'sale_name'=>$vo['truename']
                    ];        
                    $tmp['contact_num'] = Db::name('contact')->where($map)->count();
                    $tmp['hjzx_num'] = Db::name('hjzx_record')->where($map)->count();
                    if ($tmp['hjzx_num'] == 0) {
                        continue;
                    }
                    $map[] = ['bill','>',0];
                    $tmp['bill_num'] = Db::name('hjzx_record')->where($map)->count();
                    $tmp['bill_total'] = Db::name('hjzx_record')->where($map)->sum('bill');
                    $tmp['bill_ratio'] = $tmp['hjzx_num']?round($tmp['bill_num']/$tmp['hjzx_num']*100,2):0;

                    $list[] = $tmp;
                }
                $start_time = $next_time;
            }
        }


        if (isSearchParam('start_bill') || isSearchParam('end_bill')) {
            $start_bill = emptyDef(input('start_bill'),0);
            $end_bill = emptyDef(input('end_bill'),99999999);
            foreach ($list as $k => $vo) {
                if ($vo['bill_total'] < $start_bill || $vo['bill_total'] > $end_bill) {
                    unset($list[$k]);
                }
            }
        }

        $sales = Db::name('sale')->select();
        $sales = arrayParamExtract($sales,'id','truename');

        $teams = Db::name('team')->select();
        $teams = arrayParamExtract($teams,'id','name');
        $search_params = [
            [
                ['key'=>'time_particle','name'=>'时间颗粒度','type'=>'select1','params'=>[
                    '0'=>'小时','1'=>'天','2'=>'月','10'=>'归总'
                ]],
                ['key'=>'sale_id','name'=>'销售','type'=>'select2_1','params'=>$sales],
                ['key'=>'team_id','name'=>'团队','type'=>'select2_1','params'=>$teams],
            ],[
                ['key'=>'start_time','name'=>'开始时间','type'=>'date'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'date'],
                ['key'=>'start_bill','name'=>'开始时长','type'=>'text'],
                ['key'=>'end_bill','name'=>'结束时长','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
        $page_info = $this->page_info;
        $page_info['title'] = '呼叫汇总';

        $total = ['bill_ratio'=>0,'bill_total'=>0,'bill_avg'=>0];
        if (!empty($list)) {
            $total['bill_ratio'] = round(array_sum(array_column($list,'bill_ratio')) / count($list),2);
            $total['bill_total'] = array_sum(array_column($list,'bill_total'));
            $total['bill_avg'] = round($total['bill_total'] / count($list),2);
        }
        

        return view('hjzx', [
            'list'=>$list,
            'page_info'=>$page_info,
            'total'=>$total
        ]);
    }

    public function hjzx_export(){
        $map = [];
        if (isSearchParam('sale_id')) {
            $map[] = ['id','=',input('sale_id')];
        }
        if (isSearchParam('team_id')) {
            $map[] = ['team_id','=',input('team_id')];
        }
        $sales = Db::name('sale')->where($map)->select();
        foreach ($sales as $k => $vo) {
            $sales[$k]['team_name'] = Db::name('team')->where('id',$vo['team_id'])->value('name');
        }
        $start_time = input('?start_time') ? strtotime(input('start_time')) : strtotime(date('Y-m-d'));
        $end_time = input('?end_time') ? strtotime(input('end_time').' 23:59:59') : strtotime(date('Y-m-d 23:59:59'));

        $list = [];
        if (input('time_particle',10) == 10) {
            foreach ($sales as $k => $vo) {
                $map = [
                    ['ctime','between',[$start_time,$end_time]],
                    ['sale_id','=',$vo['id']]
                ];
                $tmp = [
                    'time_name'=>timeDef($start_time,'','Y-m-d').'~'.timeDef($end_time,'','Y-m-d'),
                    'team_name'=>$vo['team_name'],
                    'sale_name'=>$vo['truename']
                ];        
                $tmp['contact_num'] = Db::name('contact')->where($map)->count();
                $tmp['hjzx_num'] = Db::name('hjzx_record')->where($map)->count();
                if ($tmp['hjzx_num'] == 0) {
                    continue;
                }
                $map[] = ['bill','>',0];
                $tmp['bill_num'] = Db::name('hjzx_record')->where($map)->count();
                $tmp['bill_total'] = Db::name('hjzx_record')->where($map)->sum('bill');
                $tmp['bill_ratio'] = $tmp['hjzx_num']?round($tmp['bill_num']/$tmp['hjzx_num']*100,2):0;

                $list[] = $tmp;
            }
        }else{
            switch (input('time_particle',1)) {
                case '0': $time_particle = '+1 hours'; break;
                case '2': $time_particle = '+1 month'; break;
                default: $time_particle = '+1 days'; break;
            }
            while ($start_time <= $end_time) {
                $next_time = strtotime($time_particle,$start_time);
                foreach ($sales as $k => $vo) {
                    $map = [
                        ['ctime','between',[$start_time,$next_time]],
                        ['sale_id','=',$vo['id']]
                    ];
                    $tmp = [
                        'time_name'=>timeDef($start_time),
                        'team_name'=>$vo['team_name'],
                        'sale_name'=>$vo['truename']
                    ];        
                    $tmp['contact_num'] = Db::name('contact')->where($map)->count();
                    if ($tmp['contact_num'] == 0) {
                        continue;
                    }
                    $tmp['hjzx_num'] = Db::name('hjzx_record')->where($map)->count();
                    $map[] = ['bill','>',0];
                    $tmp['bill_num'] = Db::name('hjzx_record')->where($map)->count();
                    $tmp['bill_total'] = Db::name('hjzx_record')->where($map)->sum('bill');
                    $tmp['bill_ratio'] = $tmp['hjzx_num']?round($tmp['bill_num']/$tmp['hjzx_num']*100,2):0;

                    $list[] = $tmp;
                }
                $start_time = $next_time;
            }
        }


        if (isSearchParam('start_bill') || isSearchParam('end_bill')) {
            $start_bill = emptyDef(input('start_bill'),0);
            $end_bill = emptyDef(input('end_bill'),99999999);
            foreach ($list as $k => $vo) {
                if ($vo['bill_total'] < $start_bill || $vo['bill_total'] > $end_bill) {
                    unset($list[$k]);
                }
            }
        }

        $data = [];
        $title = ['时间','团队','销售','呼叫次数','接通次数','呼叫总时长','接通率','跟进次数'];
        foreach ($list as $k => $vo) {
            $tmp = [
                $vo['time_name'],$vo['team_name'],$vo['sale_name'],
                $vo['hjzx_num'],$vo['bill_num'],$vo['bill_total'],
                $vo['bill_ratio'].'%',
                $vo['contact_num'],
            ];
            // foreach ($tmp as $tmp_k => $tmp_v) {
            //     $tmp[$tmp_k] = iconv('utf-8','gbk',$tmp_v);
            // }
            $data[] = $tmp;
        }
        exportCsv(date('YmdHis'),$title,$data);
    }


   
}
